package main;

import java.util.ArrayList;

public class ThePlaceWSClock {
	
	
	private static ArrayList<Page> readableMemory = new ArrayList<Page>();
	public static ArrayList<Page> nonVolatileStorage = new ArrayList<Page>();
	public static int ARRAY_SIZE = 7;
	public static int NONVOLATILE_SIZE = 256;
	public static int hand = 0;
	public static int id = 0;
	public static float TAU = 3;
	
	
public static void populate(){
		
		for (int i = 0; i < NONVOLATILE_SIZE; i++) {
			
			nonVolatileStorage.add(createPage());
			
		}
		
	}
	
	public synchronized Page readPage(Page requestedPage) {
		
		int index;
		int id = requestedPage.id;
		boolean stop = false;
		for (int i = 0; i < readableMemory.size(); i++) {
			
			if(readableMemory.get(i).id == id){
				
				index = i;
				stop = true;
				readableMemory.get(index).r = 1;
				readableMemory.get(index).time += 1.0;
				return readableMemory.get(i);				
			}
			
		}
		return null;
		
	 }
	
	
	
	public synchronized Page requestPage(int id) {
		
		Page tempPage = nonVolatileStorage.get(id);
		add(tempPage);
		
		//int contents = page.id;
	   
		return tempPage;
	    
	    
	}
	
	public synchronized static Page createPage(){
		
		Page page = new Page();
		page.r = 1;
		page.time = 0;
		page.id = id;
		id++;
		return page;
		
	}
	
	public synchronized static void add(Page page){
		
		if(hand==6){
			hand = 0;
		}
		if(readableMemory.size() <= ARRAY_SIZE){
			readableMemory.add(page);
		}else{
			remove();
			add(page);
		}
		
	} 
	
	public synchronized static void remove(){
		
		if(readableMemory.isEmpty()){
		
			System.out.println("queue is empty");
			
		} else {
			
			
			do{
				
				if(readableMemory.get(hand).r == 0){
					
					if(readableMemory.get(hand).time < TAU){
						
						readableMemory.get(hand).time++;
						hand++;
					
					}else{
						
						readableMemory.remove(hand);
						break;
					}
					
				} else {
					
					readableMemory.get(hand).r = 0;
					hand++;
				}
				
				
				if(hand == 6){
					hand = 0;
				}
			}while(true);
		}
	}
}